package com.itheima.springbootmybatislilingguo.listener;

import com.itheima.springbootmybatislilingguo.domain.LogInfo;
import com.itheima.springbootmybatislilingguo.service.LogInfoService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

@Component
public class RabbitMQListener implements ChannelAwareMessageListener {

    @Autowired
    private LogInfoService logInfoService;

    @Override
    @RabbitListener(queues = "SpringBoot_Queue")
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        byte[] bytes = message.getBody();
        try {
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            Object object = ois.readObject();
            if (object instanceof LogInfo) {
                logInfoService.save((LogInfo) object);
            }
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            System.err.print("the message is not class 'LogInfo'\r\n");
            channel.basicNack(deliveryTag, true, false);
        }
        /*
            basicAck(long deliveryTag, boolean multiple)
            basicNack(long deliveryTag, boolean multiple, boolean requeue)
         */
    }
}
